{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# pentominoes_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/pentominoes_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/pentominoes_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Example to solves a pentomino paving problem.\n",
    "\n",
    "Given a subset of n different pentomino, the problem is to pave a square of\n",
    "size 5 x n. The problem is reduced to an exact set cover problem and encoded\n",
    "as a linear boolean problem.\n",
    "\n",
    "This problem comes from the game Katamino:\n",
    "http://boardgamegeek.com/boardgame/6931/katamino\n",
    "\n",
    "This example also includes suggestions from\n",
    "https://web.ma.utexas.edu/users/smmg/archive/1997/radin.html\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections.abc import Sequence\n",
    "from typing import Dict, List\n",
    "\n",
    "from ortools.sat.colab import flags\n",
    "from google.protobuf import text_format\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "\n",
    "_PARAMS = flags.define_string(\n",
    "    \"params\",\n",
    "    \"num_search_workers:16,log_search_progress:false,max_time_in_seconds:45\",\n",
    "    \"Sat solver parameters.\",\n",
    ")\n",
    "\n",
    "_PIECES = flags.define_string(\n",
    "    \"pieces\", \"FILNPTUVWXYZ\", \"The subset of pieces to consider.\"\n",
    ")\n",
    "\n",
    "_HEIGHT = flags.define_integer(\"height\", 5, \"The height of the box.\")\n",
    "\n",
    "\n",
    "def is_one(mask: List[List[int]], x: int, y: int, orientation: int) -> bool:\n",
    "    \"\"\"Returns true if the oriented piece is 1 at position [i][j].\n",
    "\n",
    "    The 3 bits in orientation respectively mean: transposition, symmetry by\n",
    "    x axis, symmetry by y axis.\n",
    "\n",
    "    Args:\n",
    "      mask: The shape of the piece.\n",
    "      x: position.\n",
    "      y: position.\n",
    "      orientation: between 0 and 7.\n",
    "    \"\"\"\n",
    "    if orientation & 1:\n",
    "        tmp: int = x\n",
    "        x = y\n",
    "        y = tmp\n",
    "    if orientation & 2:\n",
    "        x = len(mask[0]) - 1 - x\n",
    "    if orientation & 4:\n",
    "        y = len(mask) - 1 - y\n",
    "    return mask[y][x] == 1\n",
    "\n",
    "\n",
    "def get_height(mask: List[List[int]], orientation: int) -> int:\n",
    "    if orientation & 1:\n",
    "        return len(mask[0])\n",
    "    return len(mask)\n",
    "\n",
    "\n",
    "def get_width(mask: List[List[int]], orientation: int) -> int:\n",
    "    if orientation & 1:\n",
    "        return len(mask)\n",
    "    return len(mask[0])\n",
    "\n",
    "\n",
    "def orientation_is_redundant(mask: List[List[int]], orientation: int) -> bool:\n",
    "    \"\"\"Checks if the current rotated figure is the same as a previous rotation.\"\"\"\n",
    "    size_i: int = get_width(mask, orientation)\n",
    "    size_j: int = get_height(mask, orientation)\n",
    "    for o in range(orientation):\n",
    "        if size_i != get_width(mask, o):\n",
    "            continue\n",
    "        if size_j != get_height(mask, o):\n",
    "            continue\n",
    "\n",
    "        is_the_same: bool = True\n",
    "        for k in range(size_i):\n",
    "            if not is_the_same:\n",
    "                break\n",
    "            for l in range(size_j):\n",
    "                if not is_the_same:\n",
    "                    break\n",
    "                if is_one(mask, k, l, orientation) != is_one(mask, k, l, o):\n",
    "                    is_the_same = False\n",
    "        if is_the_same:\n",
    "            return True\n",
    "    return False\n",
    "\n",
    "\n",
    "def generate_and_solve_problem(pieces: Dict[str, List[List[int]]]) -> None:\n",
    "    \"\"\"Solves the pentominoes problem.\"\"\"\n",
    "    box_height = _HEIGHT.value\n",
    "    box_width = 5 * len(pieces) // box_height\n",
    "    print(f\"Box has dimension {box_height} * {box_width}\")\n",
    "\n",
    "    model = cp_model.CpModel()\n",
    "    position_to_variables: List[List[List[cp_model.IntVar]]] = [\n",
    "        [[] for _ in range(box_width)] for _ in range(box_height)\n",
    "    ]\n",
    "\n",
    "    for name, mask in pieces.items():\n",
    "        all_position_variables = []\n",
    "        for orientation in range(8):\n",
    "            if orientation_is_redundant(mask, orientation):\n",
    "                continue\n",
    "            piece_width = get_width(mask, orientation)\n",
    "            piece_height = get_height(mask, orientation)\n",
    "            for i in range(box_width - piece_width + 1):\n",
    "                for j in range(box_height - piece_height + 1):\n",
    "                    v = model.new_bool_var(name)\n",
    "                    all_position_variables.append(v)\n",
    "                    for k in range(piece_width):\n",
    "                        for l in range(piece_height):\n",
    "                            if is_one(mask, k, l, orientation):\n",
    "                                position_to_variables[j + l][i + k].append(v)\n",
    "\n",
    "        # Only one combination is selected.\n",
    "        model.add_exactly_one(all_position_variables)\n",
    "\n",
    "    for one_column in position_to_variables:\n",
    "        for all_pieces_in_one_position in one_column:\n",
    "            model.add_exactly_one(all_pieces_in_one_position)\n",
    "\n",
    "    # Solve the model.\n",
    "    solver = cp_model.CpSolver()\n",
    "    if _PARAMS.value:\n",
    "        text_format.Parse(_PARAMS.value, solver.parameters)\n",
    "    status = solver.solve(model)\n",
    "\n",
    "    print(\n",
    "        f\"Problem {_PIECES.value} box {box_height}*{box_width} solved in\"\n",
    "        f\" {solver.wall_time}s with status {solver.status_name(status)}\"\n",
    "    )\n",
    "\n",
    "    # Print the solution.\n",
    "    if status == cp_model.OPTIMAL:\n",
    "        for y in range(box_height):\n",
    "            line = \"\"\n",
    "            for x in range(box_width):\n",
    "                for v in position_to_variables[y][x]:\n",
    "                    if solver.BooleanValue(v):\n",
    "                        line += v.name\n",
    "                        break\n",
    "            print(line)\n",
    "\n",
    "\n",
    "def main(argv: Sequence[str]) -> None:\n",
    "    if len(argv) > 1:\n",
    "        raise app.UsageError(\"Too many command-line arguments.\")\n",
    "\n",
    "    # Pieces are stored in a matrix. mask[height][width]\n",
    "    pieces: Dict[str, List[List[int]]] = {\n",
    "        \"F\": [[0, 1, 1], [1, 1, 0], [0, 1, 0]],\n",
    "        \"I\": [[1, 1, 1, 1, 1]],\n",
    "        \"L\": [[1, 1, 1, 1], [1, 0, 0, 0]],\n",
    "        \"N\": [[1, 1, 1, 0], [0, 0, 1, 1]],\n",
    "        \"P\": [[1, 1, 1], [1, 1, 0]],\n",
    "        \"T\": [[1, 1, 1], [0, 1, 0], [0, 1, 0]],\n",
    "        \"U\": [[1, 0, 1], [1, 1, 1]],\n",
    "        \"V\": [[1, 0, 0], [1, 0, 0], [1, 1, 1]],\n",
    "        \"W\": [[1, 0, 0], [1, 1, 0], [0, 1, 1]],\n",
    "        \"X\": [[0, 1, 0], [1, 1, 1], [0, 1, 0]],\n",
    "        \"Y\": [[1, 1, 1, 1], [0, 1, 0, 0]],\n",
    "        \"Z\": [[1, 1, 0], [0, 1, 0], [0, 1, 1]],\n",
    "    }\n",
    "    selected_pieces: Dict[str, List[List[int]]] = {}\n",
    "    for p in _PIECES.value:\n",
    "        if p not in pieces:\n",
    "            print(f\"Piece {p} not found in the list of pieces\")\n",
    "            return\n",
    "        selected_pieces[p] = pieces[p]\n",
    "    if (len(selected_pieces) * 5) % _HEIGHT.value != 0:\n",
    "        print(\n",
    "            f\"The height {_HEIGHT.value} does not divide the total area\"\n",
    "            f\" {5 * len(selected_pieces)}\"\n",
    "        )\n",
    "        return\n",
    "    if _HEIGHT.value < 3 or 5 * len(selected_pieces) // _HEIGHT.value < 3:\n",
    "        print(f\"The height {_HEIGHT.value} is not compatible with the pieces.\")\n",
    "        return\n",
    "\n",
    "    generate_and_solve_problem(selected_pieces)\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
